package main

import (
	"fmt"
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type Server struct {
	Name string
	Link string
	Host string
	Port int
}

var serverList []Server = make([]Server, 0)

func main() {
	loadServerList()
	for _, server := range serverList {
		fmt.Println(server)
		checkServerHealth(&server)
	}
}

func sendDingDing(msg string) {
	//请求地址模板
	webHook := `https://oapi.dingtalk.com/robot/send?access_token=***`
	content := `{"msgtype": "text",
			"text": {"content": "` + msg + `"}
		}`
	//创建一个请求
	req, err := http.NewRequest("POST", webHook, strings.NewReader(content))
	if err != nil {
		// handle error
	}

	client := &http.Client{}
	//设置请求头
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	//发送请求
	resp, err := client.Do(req)
	//关闭请求
	defer resp.Body.Close()

	if err != nil {
		// handle error
	}
}

func checkServerHealth(server *Server) {
	addr := net.JoinHostPort(server.Host, strconv.Itoa(server.Port))
	conn, err := net.DialTimeout("tcp", addr, 3*time.Second)
	if err != nil {
		fmt.Printf("Server %s is error. %v", server.Name, err)
		msg := fmt.Sprintf("服务器: %s 访问异常，连接%s", server.Name, server.Link)
		sendDingDing(msg)
		return
	}
	fmt.Printf("Serer %s is ok.\n", server.Name)
	conn.Close()
}

func loadServerList() {
	serverList = append(serverList, Server{
		Name: "Gitlab",
		Link: "http://***:***",
		Host: "***",
		Port: ***,
	})

	serverList = append(serverList, Server{
		Name: "Gerrit",
		Link: "http://***",
		Host: "***",
		Port: 20080,
	})
}
